package com.xushi.controller;

import com.alipay.api.AlipayApiException;
import com.xushi.bean.AlipayConfig;
import com.xushi.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private AlipayConfig alipayConfig;

    public static String timeoutExpress = "2m";

    @PostMapping(value = "/alipay")
    @ResponseBody
    public void pay(@RequestParam int templateId, @RequestParam String timeId, HttpServletResponse response)
            throws IOException {
        HashMap<String, Object> successMap = new HashMap<>();
        successMap.put("code", 1);
        successMap.put("message", "success");
        HashMap<String, Object> failedMap = new HashMap<>();
        failedMap.put("code", 2);
        failedMap.put("message", "failure");

        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        String username = userDetails.getUsername();

        try {
            String result = alipayService.pay(templateId, timeId, username);
            response.setContentType("text/html;charset=" + alipayConfig.getCHARSET());
            response.getWriter().write(result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            failedMap.put("reason", e);
            response.getWriter().write(failedMap.toString());
        }

    }
}
